type UrlType =
  | string
  | Request
  | Ref<string | Request>
  | (() => string | Request);

export interface RequestOptions {
  method?: any;
  params?: any;
  headers?: any;
}

const request = async (
  url: UrlType,
  params: any,
  options: RequestOptions,
  controller?: AbortController
) => {
  const { method = ((options?.method || "GET") as string).toUpperCase() } =
    options;
  return fetch(
    method === "GET"
      ? `${url}?${new URLSearchParams(options.params)}`
      : (url as string),
    {
      method,
      signal: controller?.signal,
      headers: options.headers,
      body: method === "POST" ? JSON.stringify(params) : undefined,
    }
  );
};

export const useDefaultRequest = {
  get: (url: UrlType, params?: any, option?: RequestOptions) => {
    return request(url, params, { method: "GET", ...option });
  },
  post: (
    url: UrlType,
    params?: any,
    option?: RequestOptions,
    controller?: AbortController
  ) => {
    return request(url, params, { method: "POST", ...option }, controller);
  },
};
